﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Net;
using System.Net.Sockets;
using System.Data;
using System.Reflection;
using System.Collections;
using System.Text.RegularExpressions;
using System.Security.Principal;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using Newtonsoft.Json.Linq;

namespace FangDuShi_Front.Common
{
    /// <summary>
    /// 其他公用的一些方法
    /// </summary>
    public class GlobalUtil
    {
        /// <summary>
        /// 接卸json消息
        /// </summary>
        /// <param name="jsonMsg"></param>
        /// <param name="code"></param>
        /// <param name="msg"></param>
        public static void GetJsonMsgResult(string jsonMsg, out string code, out string msg)
        {
            code = "";
            msg = "";
            if (jsonMsg != "")
            {
                JObject msgJson = JObject.Parse(jsonMsg);
                jsonMsg = msgJson.ToString();
                code = msgJson["code"].ToString();
                msg = msgJson["msg"].ToString();
            }
        }

        /// <summary>
        /// 获取本机的MAC地址
        /// <creator>wangl</creator>
        /// <date>2012-01-07</date> 
        /// </summary>
        /// <returns></returns>
        public static string GetLocalMACAddress()
        {
            string mac = null;
            ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection queryCollection = query.Get();
            foreach (ManagementObject mo in queryCollection)
            {
                if (mo["IPEnabled"].ToString() == "True")
                    mac = mo["MacAddress"].ToString();
            }
            return (mac);

        }

        /// <summary>
        ///  获取本机的IP
        /// <creator>wangl</creator>
        /// <date>2012-01-07</date> 
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIP()
        {

            string strHostName = Dns.GetHostName(); //得到本机的主机名
            System.Net.IPHostEntry myHostinfo = System.Net.Dns.GetHostEntry(strHostName);
            string strAddr = "";
            foreach (IPAddress myIpAddress in myHostinfo.AddressList)
            {
                if (!myIpAddress.ToString().Contains(":"))
                {
                    strAddr = myIpAddress.ToString();
                    break;
                }
            }
            return strAddr;
        }

        /// <summary>
        /// 获取本机机器名
        /// </summary>
        /// <returns></returns>
        public static string GetLocalComputeName()
        {
            string strHostName = Dns.GetHostName(); //得到本机的主机名
            return strHostName;
        }

        /// <summary>
        /// 获取本机登录Windows账户
        /// </summary>
        /// <returns></returns>
        public static string GetLoalComputeLoginName()
        {
            WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            string NTName = "";
            string[] names = wp.Identity.Name.Split(new char[1] { '\\' });
            if (names.Length > 1)
            {
                NTName = names[1];
            }
            else
            {
                NTName = names[0];
            }

            return NTName;
        }

        /// <summary>
        /// 将集合类转换成DataTable
        /// <creator>wangl</creator>
        /// <date>2012-01-07</date> 
        /// </summary>
        /// <param name="list">集合</param>
        /// <returns></returns>
        public static DataTable ListToTable(IList list)
        {
            DataTable result = new DataTable();

            if (list.Count > 0)
            {
                PropertyInfo[] propertys = list[0].GetType().GetProperties();

                foreach (PropertyInfo pi in propertys)
                {
                    try
                    {
                        DataColumn column = new DataColumn();
                        Type conversionType = pi.PropertyType;
                        if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                        {
                            System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
                            conversionType = nullableConverter.UnderlyingType;
                        }

                        result.Columns.Add(pi.Name, conversionType);
                    }
                    catch
                    {
                        result.Columns.Add(pi.Name);
                    }
                }
                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(list[i], null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }


        /// <summary>
        /// 比较两个datatable的值
        /// <creator>zhongyl</creator>
        /// <date>2012-01-07</date> 
        /// </summary>
        /// <param name="dtOld">旧的DataTable对象</param>
        /// <param name="dtNew">新的DataTable对象</param>
        /// <param name="indexNameList">关键字列表(支持多个关键字)</param>
        /// <returns>字典列表中保存的是add-增加 delele-删除 update-更新 的三个列表
        /// null值为主键重复
        /// </returns>
        public static Dictionary<string, List<DataRow>> CompareDataTable(DataTable dtOld, DataTable dtNew, List<string> indexNameList, bool isNullKey = false)
        {
            Dictionary<string, List<DataRow>> dicDrList = new Dictionary<string, List<DataRow>>();
            List<DataRow> drAdd = new List<DataRow>();
            List<DataRow> drUpdate = new List<DataRow>();
            List<DataRow> drDelete = new List<DataRow>();
            if (!dtOld.Columns.Contains("GridRowStatus"))
            {
                dtOld.Columns.Add("GridRowStatus");
            }

            if (!dtNew.Columns.Contains("GridRowStatus"))
            {
                dtNew.Columns.Add("GridRowStatus");
            }

            if (indexNameList.Count < 0)
            {
                return dicDrList;
            }

            bool isIndexRepeat = false;
            DataRow[] drS;     //存放指向旧表相应行的指针
            bool bAllTheSame;  //存放某行数据是否有所变更的标志
            foreach (DataRow dr in dtNew.Rows)
            {
                //构造关键字语句
                string selectString = "";
                bool isIndexEmpty = false;  //判断主键是否为空
                for (int i = 0; i < indexNameList.Count; i++)
                {
                    string indexName = indexNameList[i];
                    if (string.IsNullOrEmpty(dtNew.Columns[indexName].DataType.Name))
                    {
                        dtNew.Columns[indexName].DataType = typeof(string);
                    }
                    if (i == indexNameList.Count - 1)
                    {
                        if (dtNew.Columns[indexName].DataType.Name == typeof(string).Name)
                        {
                            selectString += indexName + "='" + dr[indexName].ToString() + "'";
                        }
                        else
                        {
                            selectString += indexName + "=" + dr[indexName].ToString();
                        }
                    }
                    else
                    {
                        if (dtNew.Columns[indexName].DataType.Name == typeof(string).Name)
                        {
                            selectString += indexName + "='" + dr[indexName].ToString() + "' AND ";
                        }
                        else
                        {
                            selectString += indexName + "=" + dr[indexName].ToString() + " AND ";
                        }

                    }
                    //判断主键是否为空，自增类型的新增行
                    if (dr[indexName].ToString() == "")
                    {
                        //if (isNullKey)
                        //{
                        isIndexEmpty = true;
                        //}
                        //else
                        //{
                        //    return null;
                        //}
                    }
                }

                if (isIndexEmpty)
                {
                    drAdd.Add(dr);
                    dr["GridRowStatus"] = "Added";
                    continue;
                }
                DataRow[] drsNew = dtNew.Select(selectString);
                if (drsNew.Length > 1)
                {
                    isIndexRepeat = true;
                    break;
                }

                drS = dtOld.Select(selectString);  //检索旧表，看是否有对应行
                if (drS.Length > 0)  //旧表有对应行
                {

                    bAllTheSame = true;
                    for (int i = 0; i < dtOld.Columns.Count; i++)  //看是否某列的值被变更
                    {
                        if (dtOld.Columns[i].DataType.Name == typeof(byte[]).Name)
                        {
                            if (dr[i] != DBNull.Value && drS[0][i] != DBNull.Value)
                            {
                                byte[] by1 = (byte[])dr[i];
                                byte[] by2 = (byte[])drS[0][i];
                                if (by1 != by2)
                                {
                                    bAllTheSame = false;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            if (dr[i].ToString().CompareTo(drS[0][i].ToString()) != 0) //有变更
                            {
                                bAllTheSame = false;
                                break;
                            }
                        }
                    }
                    if (bAllTheSame)  //所有列未被变更
                    {
                        dr["GridRowStatus"] = "UnChanged";
                        drS[0]["GridRowStatus"] = "UnChanged";
                    }
                    else             //有些列被变更
                    {
                        drUpdate.Add(dr);
                        dr["GridRowStatus"] = "Modified";
                        drS[0]["GridRowStatus"] = "Modified";
                    }

                    if (drS.Length > 1)
                    {
                        for (int i = 1; i < drS.Length; i++)
                        {
                            drAdd.Add(drS[i]);
                            drS[i]["GridRowStatus"] = "Added";
                        }
                    }

                }
                else    //旧表中无对应行
                {
                    drAdd.Add(dr);
                    dr["GridRowStatus"] = "Added";
                }
            }//至此，新表标志完毕，旧表只剩删除行未被标志

            if (!isIndexRepeat)
            {
                foreach (DataRow dr in dtOld.Rows)
                {
                    if (dr["GridRowStatus"].ToString().Length == 0)   //旧表中此行数据未被标志
                    {
                        dr["GridRowStatus"] = "Delete";
                        drDelete.Add(dr);
                    }
                }//至此，旧表删除行标志完毕
                if (dtOld.Columns.Contains("GridRowStatus"))
                {
                    dtOld.Columns.Remove("GridRowStatus");
                }

                if (dtNew.Columns.Contains("GridRowStatus"))
                {
                    dtNew.Columns.Remove("GridRowStatus");
                }

                dicDrList.Add("add", drAdd);
                dicDrList.Add("delete", drDelete);
                dicDrList.Add("update", drUpdate);
                return dicDrList;
            }
            else
            {
                return null;
            }

        }
        /// <summary>
        /// 验证编码有效性
        /// 如果验证无效提示信息为 :
        /// 编码只允许大写字母、数字和 - [ ] ( ) . 且不能为空
        /// <creator>wangl</creator>
        /// <date>2012-02-21</date> 
        /// </summary>
        /// <param name="code"></param>
        /// <returns>true-有效 false-无效</returns>
        public static bool CheckCodeValidate(string code)
        {
            bool result = false;
            Regex reg = new Regex(@"^[A-Z0-9\-\[\]().]+$");
            result = reg.IsMatch(code);
            return result;
        }

        /// <summary>
        /// 手机号码验证(11位或12位(0开始))
        /// <creator>rend</creator>
        /// <date>2012-02-25</date> 
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public static bool CheckMobilValidate(string mobile)
        {
            bool result = false;
            Regex reg = new Regex(@"^\d{11}$|0\d{11}$");
            result = reg.IsMatch(mobile);
            return result;
        }

        /// <summary>
        /// 电话号码(可输入分机号)/手机号码
        /// 输入格式1 (0574)1234567|(0574)12345678|(574)1234567|(574)12345678|1234567|12345678
        /// 输入格式2 0574-1234567 |以下格式规则同上
        /// 输入格式3 格式1,格式2后都还可以再输入以下内容(分机号)  *123(数字,个数不限) -123(数字,个数不限)
        /// 输入格式4 同手机号码格式
        /// <creator>rend</creator>
        /// <date>2012-02-25</date> 
        /// </summary>
        /// <param name="tel"></param>
        /// <returns></returns>
        public static bool CheckTelExtensionAndMobilValidate(string tel)
        {
            bool result = false;
            Regex reg = new Regex(@"(^(\d{11}|0\d{11}))$|(^((\(\d{3,4}\))|(\d{3,4}-))?(\d{7,8}([-,*]\d*)?))$");
            result = reg.IsMatch(tel);
            return result;
        }

        /// <summary>
        /// 电话号码/手机号码
        /// 输入格式1 (0574)1234567|(0574)12345678|(574)1234567|(574)12345678|1234567|12345678
        /// 输入格式2 0574-1234567 |以下格式规则同上
        /// 输入格式3 同手机号码格式
        /// <creator>rend</creator>
        /// <date>2012-02-25</date> 
        /// </summary>
        /// <param name="tel"></param>
        /// <returns></returns>
        public static bool CheckTelAndMobilValidate(string tel)
        {
            bool result = false;
            Regex reg = new Regex(@"(^(\d{11}|0\d{11}))$|(^((\(\d{3,4}\))|(\d{3,4}-))?(\d{7,8}))$");
            result = reg.IsMatch(tel);
            return result;
        }


        /// <summary>
        /// 电话号码(可输入分机号)
        /// 输入格式1 (0574)1234567|(0574)12345678|(574)1234567|(574)12345678|1234567|12345678
        /// 输入格式2 0574-1234567 |以下格式规则同上
        /// 输入格式3 格式1,格式2后都还可以再输入以下内容(分机号)  *123(数字,个数不限) -123(数字,个数不限)
        /// <creator>rend</creator>
        /// <date>2012-02-25</date> 
        /// </summary>
        /// <param name="tel"></param>
        /// <returns></returns>
        public static bool CheckTelExtensionValidate(string tel)
        {
            bool result = false;
            Regex reg = new Regex(@"^(((\(\d{3,4}\))|(\d{3,4}-))?(\d{7,8}([-,*]\d*)?))$");
            result = reg.IsMatch(tel);
            return result;
        }

        /// <summary>
        /// 电话号码
        /// 输入格式1 (0574)1234567|(0574)12345678|(574)1234567|(574)12345678|1234567|12345678
        /// 输入格式2 0574-1234567 |以下格式规则同上
        /// <creator>rend</creator>
        /// <date>2012-02-25</date> 
        /// </summary>
        /// <param name="tel"></param>
        /// <returns></returns>
        public static bool CheckTelValidate(string tel)
        {
            bool result = false;
            Regex reg = new Regex(@"^(((\(\d{3,4}\))|(\d{3,4}-))?(\d{7,8}))$");
            result = reg.IsMatch(tel);
            return result;
        }



        /// <summary>
        /// EMail
        /// <creator>rend</creator>
        /// <date>2012-02-25</date> 
        /// </summary>
        /// <param name="eMail"></param>
        /// <returns></returns>
        public static bool CheckEMailValidate(string eMail)
        {
            bool result = false;
            Regex reg = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
            result = reg.IsMatch(eMail);
            return result;
        }

        /// <summary>
        /// 验证序列号有效性
        /// 序列号只允许大写字母、数字和 - 且不能为空
        /// <creator>wangl</creator>
        /// <date>2012-02-21</date> 
        /// </summary>
        /// <param name="code"></param>
        /// <returns>true-有效 false-无效</returns>
        public static bool CheckSerialValidate(string code)
        {
            bool result = false;
            Regex reg = new Regex(@"^[A-Z0-9\-]+$");
            result = reg.IsMatch(code);
            return result;
        }

        ///// <summary>
        ///// .NET数据类型转化为SqlServer类型
        ///// <creator>wangl</creator>
        ///// <date>2012-03-20</date> 
        ///// </summary>
        ///// <param name="netType"></param>
        ///// <returns></returns>
        //public static SqlDbType ConvertNetTypeToSqlType(Type netType)
        //{
        //    SqlDbType sqlDbType = SqlDbType.VarChar;
        //    switch (netType.Name)
        //    {
        //        case "Int32": { sqlDbType = SqlDbType.Int; break; }
        //        case "Int64": { sqlDbType = SqlDbType.BigInt; break; }
        //        case "Byte[]": { sqlDbType = SqlDbType.Binary; break; }
        //        case "Boolean": { sqlDbType = SqlDbType.Bit; break; }
        //        case "String": { sqlDbType = SqlDbType.Bit; break; }
        //    }
        //    return sqlDbType;
        //}


        /// <summary>
        /// 图像转换成二进制
        /// <creator>wangl</creator>
        /// <date>2012-03-27</date>
        /// </summary>
        /// <param name="Picture"></param>
        /// <returns></returns> 
        public static byte[] ImageToByte(Image Picture)
        {
            MemoryStream ms = new MemoryStream();
            if (Picture == null)
                return new byte[ms.Length];
            Picture.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] BPicture = new byte[ms.Length];
            BPicture = ms.GetBuffer();
            return BPicture;
        }
        /// <summary>
        /// 二进制转换为图像
        /// <creator>wangl</creator>
        /// <date>2012-03-27</date>
        /// </summary>
        /// <param name="btImage"></param>
        /// <returns></returns>
        public static Image ByteToImage(byte[] btImage)
        {
            if (btImage == null || btImage.Length == 0)
                return null;
            System.IO.MemoryStream ms = new System.IO.MemoryStream(btImage);
            System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
            return image;
        }
        /// <summary>
        /// 生成缩略图重载方法1，返回缩略图的Image对象
        /// <creator>wangl</creator>
        /// <date>2012-03-27</date>
        /// </summary>
        /// <param name="Width">缩略图的宽度</param>
        /// <param name="Height">缩略图的高度</param>
        /// <returns>缩略图的Image对象</returns>
        public static Image GetReducedImage(Image ResourceImage, int Width, int Height)
        {
            try
            {
                Image ReducedImage;
                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
                ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
                return ReducedImage;
            }
            catch
            {
                return null;
            }
        }
        private static bool ThumbnailCallback()
        {
            return false;
        }

        /// <summary>
        /// 图像灰度处理
        /// <creator>zhangy</creator>
        /// <date>2012-2-20</date>
        /// wangl 2012-04-06 移动这里
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        public static Image ImageToGary(Image img)
        {
            Bitmap currentBitmap = new Bitmap(img);
            Graphics g = Graphics.FromImage(currentBitmap);
            ImageAttributes ia = new ImageAttributes();
            float[][] colorMatrix =   {    
            new   float[]   {0.299f,   0.299f,   0.299f,   0,   0},                
            new   float[]   {0.587f,   0.587f,   0.587f,   0,   0},                
            new   float[]   {0.114f,   0.114f,   0.114f,   0,   0},                
            new   float[]   {0,   0,   0,   1,   0},                  
            new   float[]   {0,   0,   0,   0,   1}};
            ColorMatrix cm = new ColorMatrix(colorMatrix);
            ia.SetColorMatrix(cm, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            g.DrawImage(currentBitmap, new Rectangle(0, 0, currentBitmap.Width, currentBitmap.Height), 0, 0, currentBitmap.Width, currentBitmap.Height, GraphicsUnit.Pixel, ia);
            Image grayimg = currentBitmap;
            g.Dispose();
            return grayimg;
        }
        /// <summary>
        /// 压缩图片,按比例缩小
        /// </summary>
        /// <param name="srcImage"></param>
        /// <returns></returns>
        public static Image CompressImage(Image srcImage)
        {
            Image desImage = null;
            if (srcImage.Width > 1024)
            {
                decimal d = (decimal)srcImage.Width / (decimal)srcImage.Height;
                decimal h = 1024 / d;
                desImage = Common.GlobalUtil.GetReducedImage(srcImage, 1024, (int)h);
            }
            else if (srcImage.Height > 768)
            {
                decimal d = (decimal)srcImage.Width / (decimal)srcImage.Height;
                decimal w = 768 * d;
                desImage = Common.GlobalUtil.GetReducedImage(srcImage, (int)w, 768);
            }
            else
            {
                desImage = srcImage;
            }

            return desImage;
        }

        public static int ProgressStepCount
        {
            get;
            set;
        }
        /// <summary>
        /// DataTable任意两行交换
        /// </summary>
        /// <param name="index1"></param>
        /// <param name="index2"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static DataTable SwapRow(int index1, int index2, DataTable dt)
        {
            DataRow dr = dt.NewRow();
            dr.ItemArray = dt.Rows[index1].ItemArray;
            dt.Rows[index1].ItemArray = dt.Rows[index2].ItemArray;
            dt.Rows[index2].ItemArray = dr.ItemArray;
            return dt;
        }

    }
    //[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
    //public class LastModifiedAttribute : Attribute
    //{
    //    /// <summary>
    //    /// 修改日期
    //    /// </summary>
    //    private DateTime dateModified;
    //    /// <summary>
    //    /// 类修改属性
    //    /// </summary>
    //    /// <param name="dateModified">修改日期 年-月-日</param>
    //    public LastModifiedAttribute(string dateModified)
    //    {
    //        this.dateModified = DateTime.Parse(dateModified);

    //    }
    //    /// <summary>
    //    /// 修改日期
    //    /// </summary>
    //    public DateTime DateModified
    //    {
    //        get
    //        {
    //            return dateModified;
    //        }

    //    }
    //}


}
